package com.earnings.okhttputils.utils.car.http;

import com.earnings.okhttputils.utils.OkHttp.callback.Callback;
import com.earnings.okhttputils.utils.bean.CarBaseBean;
import com.earnings.okhttputils.utils.https.JsonGenericsSerializator;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.ParameterizedType;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by HOHO on 2017/4/25.
 */

public abstract class GodHttpDataCallback<T> extends Callback<String> {

    @Override
    public String parseNetworkResponse(Response response, int id) throws Exception {
        return response.body().string();
    }

    @Override
    public void onError(Call call, Exception e, int id) {
        GodLog.Log(e.toString());
        e.printStackTrace();
        onFail(id, e.toString());
    }

    @Override
    public void onResponse(String response, int id) {
        GodLog.Log(response);
        try {
            JsonGenericsSerializator json = new JsonGenericsSerializator();
            Gson gson = new Gson();
            // response
            CarBaseBean entity = json.transform(response, CarBaseBean.class);
            //请求状态成功时
            if (GodHttpStatus.STATUS_SUCCESS == entity.getStatus()) {
                T object = null;
                Class<T> entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];//相当于T.class
                if (entity.getData() != null) {
                    if (entityClass == JSONObject.class)
                        object = (T) new JSONObject(entity.getData().toString());
                    else if (entityClass == String.class)
                        object = (T) entity.getData().toString().substring(1, entity.getData().toString().length() - 1);
                    else object = gson.fromJson(entity.getData(), entityClass);
                }

                onSuccess(object, entity.getMessage(), response);
            } else {
                onFail(entity.getStatus(), entity.getMessage());
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public abstract void onSuccess(T data, String msg, String response);

    public abstract void onFail(int code, String msg);
}
